package cn.cloudreal.cbms.medium.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;

import cn.cloudreal.cbms.common.util.BaseDAO;
import cn.cloudreal.cbms.common.util.Constants;
import cn.cloudreal.cbms.common.util.DatadicContext;
import cn.cloudreal.cbms.common.util.PageBean;
import cn.cloudreal.cbms.medium.dao.MediumDao;
import cn.cloudreal.cbms.vo.Dictionary;
import cn.cloudreal.cbms.vo.Medium;
import cn.cloudreal.cbms.vo.ProjectMedium;
import cn.cloudreal.cbms.vo.UserInfo;

public class MediumDaoImpl extends SqlMapClientDaoSupport implements MediumDao {

    /** 日志工具类实例 */
    private static final Logger log = Logger.getLogger(MediumDaoImpl.class);
    private final String FIND_MediumList = "medium.findMediumList";
    private final String FIND_countMedium = "medium.countMedium";
    private final String DEL_Medium = "medium.delMedium";
    private final String ADD_Medium = "medium.addMedium";
    private final String FIND_MediumByID = "medium.findMediumById";
    private final String UPDATE_Medium = "medium.updateMedium";
    private final String FIND_MediumBYMediaID = "medium.findMediumByMediaID";
    private final String FIND_MediumByMediumID = "medium.findMediumByMediumID";
    private final String FIND_MediumByMediumName = "medium.findMediumByMediumName";
    private final String FIND_projectMedium = "projectmedium.findProjectmediumByMediumId";

    private Connection con = null;
    private PreparedStatement pst = null;
    private ResultSet rs = null;

    /**
     * 分页查找媒介
     */
    public List findMediumList(PageBean page, Medium medium) {
        // 打印进入方法体日志
        if (log.isInfoEnabled()) {
            log.info("Enter MediumDaoImpl findMediumList() method");
        }
        int totalCount = (Integer) getSqlMapClientTemplate().queryForObject(FIND_countMedium, medium);
        page.setTotalRecords(totalCount);
        if (totalCount == 0) {
            return null;
        }
        List<Dictionary> citylist = DatadicContext.getInstance().getSubDatadicByCode("-1","CITY"); // 地市List
        List<List> list_01 = new ArrayList<List>();
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("pageno", page.getPageNo());
        param.put("pagesize", page.getPageSize());
        param.put("mediaID", medium.getMediaID()); // 媒体编号
        param.put("mediumID", medium.getMediumID()); // 媒介编号
        param.put("mediumName", medium.getMediumName()); // 媒介名称
        param.put("keySql", medium.getExtAttribute02());
        List<Medium> result = this.getSqlMapClientTemplate().queryForList(FIND_MediumList, param);
        String[] keyArr = medium.getExtAttribute01().split(",");
        Map hashMap  = new HashMap();
        for(int i=0;i<result.size();i++) {
            hashMap = (Map) result.get(i);
            List list = new ArrayList();
            list.add(hashMap.get("id").toString());
            list.add(hashMap.get("mediumName").toString());
            list.add(hashMap.get("mediaName").toString());
            list.add(medium.getExtAttribute03());//媒体类型
            list.add(hashMap.get("contractYear").toString());
            for (int j = 0; j < citylist.size(); j++) {
                if(citylist.get(j).getId().equals(hashMap.get("city").toString())){
                    list.add(citylist.get(j).getDatavalue());
                    break;
                }
            }
            for (int j = 0; j < keyArr.length; j++) {
                String keyStr = keyArr[j];
                if(!"".equals(keyStr.trim())){
                    list.add((hashMap.get(keyStr) == null) ? "" : hashMap.get(keyStr).toString().trim());
                }
            }
                list_01.add(list);
           }
//        for (int i = 0; i < list_01.size(); i++) {
//            for(int j=0;j<list_01.get(i).size();j++){
//                System.out.println(list_01.get(i).get(j));
//            }
//            System.out.println("=====");
//        }
        
        // 打印退出方法体日志
        if (log.isInfoEnabled()) {
            log.info("Exit MediumDaoImpl findMediumList() method");
        }

        return list_01;
    }

    public List findAllMedium(PageBean page, Medium medium, String key,String keySql) {

        int totalCount = (Integer) getSqlMapClientTemplate().queryForObject(FIND_countMedium, medium);
        page.setTotalRecords(totalCount);
        if (totalCount == 0) {
            return null;
        }

        String[] keyArr = key.split(",");
        int keyArrLength= keyArr.length-1;
        List<List> list_01 = new ArrayList<List>();
        String sql = "SELECT TOP "
                + page.getPageSize()
                + " a.id,a.mediumName,b.mediaName as mediaName,a.mediumAbility,a.contractYear "
                + keySql + " FROM T_CB_MEDIUM a,T_CB_MEDIASUMM b,T_CB_MEDIAPRICE c  WHERE  " + " (id NOT IN (SELECT TOP (" + page.getPageSize() + "*("
                + page.getPageNo() + "-1)) id " + "FROM T_CB_MEDIUM z,T_CB_MEDIASUMM y,T_CB_MEDIAPRICE x "
                + "where z.mediaID=y.mediaID and z.mediaID=" + medium.getMediaID() + " and x.priceID=a.priceID  ORDER BY id desc)) "
                + "and a.mediaID=b.mediaID and a.mediaID=" + medium.getMediaID() + " and c.priceID=a.priceID ";
        if (medium.getMediumName() != null && !"".equals(medium.getMediumName())) {
            sql += " and a.mediumName LIKE '%" + medium.getMediumName() + "%' ";
        }
        sql += " ORDER BY id desc";
        System.out.println(sql);
        try {
            con = BaseDAO.getConn();
            pst = con.prepareStatement(sql);
            rs = pst.executeQuery();
            while (rs.next()) {
                List list = new ArrayList();
                list.add(String.valueOf(rs.getInt("id")));
                list.add(rs.getString("mediumName"));
                list.add(rs.getString("mediaName"));
                list.add(rs.getString("contractYear"));
                list.add(rs.getInt("mediumAbility"));
                for (int i = 0; i < keyArrLength; i++) {
                    String keyStr = keyArr[i];
                    if(!"".equals(keyStr.trim())){
                        list.add(rs.getString((i+5)));
                    }
                }
                    list_01.add(list);
            }
        }
        catch (SQLException e) {
            // TODO 自动生成 catch 块
            e.printStackTrace();
        }
        finally {
            BaseDAO.closeAll(con, pst, rs);
        }
        return list_01;
    }

    /**
     * 删除媒介
     */
    public void delMedium(int id) {
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("id", id);
        this.getSqlMapClientTemplate().delete(DEL_Medium, param);
    }

    /**
     * 添加媒介
     */
    public int addMedium(Medium medium) {
        Integer num = (Integer) this.getSqlMapClientTemplate().insert(ADD_Medium, medium);
        return num;
    }

    /**
     * 根据ID查找媒介
     */
    public Medium findMediumById(int id) {
        Medium m = (Medium) this.getSqlMapClientTemplate().queryForObject(FIND_MediumByID, id);
        return m;
    }

    /**
     * 修改媒介
     */
    public int udpateMedium(Medium medium) {
        int num = this.getSqlMapClientTemplate().update(UPDATE_Medium, medium);
        return num;
    }

    /**
     * 根据媒体编号查询媒介
     */
    public List<Medium> findMediumByMediaID(int mediaID) {
        List<Medium> list = this.getSqlMapClientTemplate().queryForList(FIND_MediumBYMediaID, mediaID);
        return list;
    }

    /**
     * 根据媒介编号查询媒介
     */
    public List<Medium> findMediumByMediumID(String mediumID) {
        List<Medium> list = this.getSqlMapClientTemplate().queryForList(FIND_MediumByMediumID, mediumID);
        return list;
    }

    /**
     * 根据媒介名称查询媒介
     */
    public List<Medium> findMediumByMediumName(String mediumName) {
        UserInfo userInfo = (UserInfo) ServletActionContext.getRequest().getSession().getAttribute(Constants.SESSIONPRKEY);
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        String nowDate = sf.format(date);
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("mediumName", mediumName);
        param.put("city", userInfo.getUsercity());
        List<Medium> list = this.getSqlMapClientTemplate().queryForList(FIND_MediumByMediumName, param);
        return list;
    }

    public List<ProjectMedium> findProjectmediumByMediumId(int mediumId) {
        List<ProjectMedium> list = this.getSqlMapClientTemplate().queryForList(FIND_projectMedium, mediumId);
        return list;
    }
}
